// axios.ts
import axios from "axios";

import type {
    AxiosInstance,
    AxiosRequestConfig,
    InternalAxiosRequestConfig,
    AxiosResponse,
} from "axios";


// 创建 Axios 实例
const axiosInstance: AxiosInstance = axios.create({
    baseURL: import.meta.env.VITE_API_BASE_URL as string, // 根据实际情况配置 baseURL
    timeout: 180000, // 设置超时时间
});

// 请求拦截器
axiosInstance.interceptors.request.use(
    (config: InternalAxiosRequestConfig) => {
        // 在这里添加请求拦截逻辑，例如添加 token 等
        if (!config.headers['Content-Type'] && !(config.data instanceof FormData)) {
            config.headers['Content-Type'] = 'application/json';
        }
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

// 响应拦截器
axiosInstance.interceptors.response.use(
    (response: AxiosResponse) => {
        // 在这里添加响应拦截逻辑，例如处理错误信息等
        return response;
    },
    (error) => {
        return Promise.reject(error);
    }
);

export function setAuthHeader(token: string | null) {
    if (token) {
        axiosInstance.defaults.headers.common['Authorization'] = `Bearer ${token}`;
    } else {
        delete axiosInstance.defaults.headers.common['Authorization'];
    }
}


export default axiosInstance;
